//go:build !windows
// +build !windows

package service

import (
	"miao-wails/backed/structs/idp"
	"os"
	"runtime"
	"strings"
)

func (s idpService) getSysInfo() (out idp.Sys, err error) {
	var (
		hostname  string
		osName    string
		osVersion string
		kernel    string
		arch      string
		vendor    string
		product   string
		serial    string
	)
	hostname, err = os.Hostname()
	if err != nil {
		return
	}
	// osInfo
	var osRelease []byte
	osRelease, err = os.ReadFile("/etc/os-release")
	if err != nil {
		return
	}
	osInfo := make(map[string]string)
	for _, line := range strings.Split(string(osRelease), "\n") {
		if strings.Contains(line, "=") {
			parts := strings.SplitN(line, "=", 2)
			key := parts[0]
			value := strings.Trim(parts[1], `"`)
			osInfo[key] = value
		}
	}
	osName = osInfo["NAME"]
	osVersion = osInfo["VERSION"]
	// 内核
	var kernelBS []byte
	kernelBS, err = os.ReadFile("/proc/version")
	if err != nil {
		return
	}
	kernel = strings.TrimSpace(string(kernelBS))
	arch := runtime.GOARCH
	vendor, err = s.readDMIFile("/sys/class/dmi/id/sys_vendor")
	if err != nil {
		vendor = "<未知>"
	}
	product, err = s.readDMIFile("/sys/class/dmi/id/product_name")
	if err != nil {
		product = "<未知>"
	}
	serial, err = s.readDMIFile("/sys/class/dmi/id/product_serial")
	if err != nil {
		serial = "<未知>"
	}
	out = idp.Sys{
		HostName:  hostname,
		OsName:    osName,
		OsVersion: osVersion,
		Kernel:    kernel,
		Arch:      arch,
		Vendor:    vendor,
		Product:   product,
		Serial:    serial,
	}
	return
}

func (s idpService) getCpu() (out idp.Cpu, err error) {
	// todo
}

func (s idpService) readDMIFile(path string) (string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(data)), nil
}
func (s idpService) getDns() (str string, err error) {
	data, err := os.ReadFile("/etc/resolv.conf")
	if err != nil {
		return
	}
	for _, line := range strings.Split(string(data), "\n") {
		if strings.HasPrefix(line, "nameserver") {
			fields := strings.Fields(line)
			if len(fields) >= 2 {
				str = fields[1]
			}
		}
	}
	return
}
